<template>
  <div class="view-fill">
    <div v-show="!assetDetailInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button :disabled="!canSave" @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-fiscalPeriodName>
                {{ formInfo.data.fiscalPeriodName }}
              </template>
            </page-form>
            <p style="color: red">
              &nbsp; &nbsp; &nbsp; &nbsp;
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注意：
              运行资产折旧或摊销后，将生成本期折旧记录，且无法取消
            </p>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-addProduct>
                <el-button
                  :disabled="!formInfo.data.fiscalPeriodId"
                  @click="addProduct"
                >
                  添加资产
                </el-button>
              </template>
              <template v-slot:filter-all>
                <el-button
                  :disabled="!formInfo.data.fiscalPeriodId"
                  @click="addAllProduct"
                >
                  添加全部资产
                </el-button>
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                >
                  删除资产
                </el-button>
              </template>
              <template v-slot:filter-productCodeScan>
                <ScanInputBox
                  :api="assetCardScanForDepreciation"
                  :disabled="!formInfo.data.fiscalPeriodId"
                  :query="scanInfo.query"
                  :is-finance-asset="true"
                  @callback="onCallBackScanData"
                />
              </template>
            </page-filter>
            <div class="flex_full_item">
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <page-table
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :summary="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-assetName="scope">
                    <span class="slip-edit" @click="showAssetDetail(scope.row)">
                      {{ scope.row.assetName }}
                    </span>
                  </template>
                </page-table>
              </el-form>
              <!-- <vxe-table
                ref="xTable"
                border
                show-overflow
                max-height="400"
                keep-source
                align="center"
                :row-config="{ isHover: true }"
                :show-footer="true"
                :footer-method="footerMethod"
                @checkbox-change="selectChange"
                @checkbox-all="toggleAllPaperSelect"
              >
                <vxe-column type="checkbox" width="60"></vxe-column>
                <vxe-column title="序号" type="seq" width="100"></vxe-column>
                <vxe-column
                  v-for="(item, index) in tableInfo.fieldList.filter(
                    (item) => !item.hidden
                  )"
                  :key="index"
                  :title="item.label"
                  :min-width="120"
                  :field="item.value"
                >
                  <template slot-scope="scope">
                    <span
                      v-if="item.type === 'slot'"
                      class="slip-edit"
                      @click="showAssetDetail(scope.row)"
                    >
                      {{ scope.row.assetName }}
                    </span>
                    <span v-else>
                      {{ scope.row[item.value] }}
                    </span>
                  </template>
                </vxe-column>
                <vxe-column title="操作" width="100" fixed="right">
                  <template slot-scope="scope">
                    <el-popconfirm
                      placement="bottom-end"
                      title="删除后将改变数据,是否继续？"
                      icon="WarningFilled"
                      @confirm="removeProduct(scope.row)"
                    >
                      <a slot="reference" class="actionBtn">删除</a>
                    </el-popconfirm>
                  </template>
                </vxe-column>
              </vxe-table> -->
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <Select-asset
      v-if="selectAssetInfo.visible"
      :table-key="selectAssetInfo.tableKey"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :check-box="true"
      @callback="callBackAsset"
    />
    <!-- 详情页 -->
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
  </div>
</template>
<script setup>
import { getCustomizeSetting } from '@/api/customize'
import { saveAssetDepreciation } from '@/api/asset.js'
import {
  getCurrentFiscalPeriod,
  assetCardScanForDepreciation,
  getAssetCardAll,
} from '@/api/core.js'
import moment from 'moment'
// import XEUtils from 'xe-utils'
import ScanInputBox from '@/components/SelectAsset/ScanInputBox'
const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'id'])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const scanInfo = ref({
  query: {
    assetStatus: '1,3',
    assetSourceAuth: true,
  },
})
const formInfo = ref({
  disabled: false,
  ref: null,
  data: {
    fiscalPeriodId: '',
    fiscalPeriodName: '',
  },
  fieldList: [
    { label: '当前会计期间', value: 'fiscalPeriodName', type: 'slot' },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'date',
      TimePickerOptions: {},
    },
  ],
  rules: {
    fiscalPeriodName: [
      {
        required: true,
        message: '请选择当前会计期间',
        trigger: 'change',
      },
    ],
    businessDate: [
      {
        required: true,
        message: '请选择业务日期',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '180px',
})
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {},
  },
  list: [
    {
      type: 'slot',
      value: 'addProduct',
    },
    {
      type: 'slot',
      value: 'all',
    },
    {
      type: 'slot',
      value: 'removeProduct',
    },
    {
      type: 'slot',
      value: 'productCodeScan',
    },
  ],
})
const tableInfo = ref({
  summaryFieldList: [
    {
      value: 'monthDeprAmount',
      formatter: proxy.$fn.TripartiteMethodAsset,
    },
  ],
  data: [],
  selections: [],
  fieldList: [],
})
const selectAssetInfo = ref({
  visible: false,
  tableKey:
    'addCoreAssetByDepreciation-com.slip.spd.entity.vo.core.CoreAssetVO',
  query: {
    queryParams: {
      postingDateFilter: true,
      netAmountZeroFilter: true,
      rollBackDeprFilter: true,
      afterFiscalPeriodDateFilter: true,
      availableMonth: true,
    },
    queryMap: {
      assetStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,3',
      },
      assetSourceAuth: {
        asTbName: 'core_asset,core_asset',
        columnName: 'use_dept_id,depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'assetSourceAuth',
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      status: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 6,
      },
      isLocked: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      accrualMark: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
  },
})
const allAssetFilterInfo = ref({
  queryParams: {},
  queryMap: {},
  customizeUserVO: {},
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveProduct = computed(() => {
  console.log(tableInfo.value.selections)
  return tableInfo.value.selections.length
})

onMounted(() => {
  proxy.$nextTick(() => {
    //获取当前会计期间
    getCurrentFiscalPeriod(2).then((res) => {
      if (res && res.success) {
        formInfo.value.data.fiscalPeriodName = res.data.name
        formInfo.value.data['fiscalPeriodId'] = res.data.id
        formInfo.value.fieldList.forEach((item) => {
          if (item.value === 'businessDate') {
            item.TimePickerOptions = {
              disabledDate(time) {
                return (
                  time.getTime() <
                  new Date(res.data.startDate).getTime() - 24 * 60 * 60 * 1000
                )
              },
            }
          }
        })
      }
    })
  })
})

setData()
function setData() {
  proxy.$nextTick(() => {
    tableInfo.value.fieldList = Object.values({
      ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    })
  })
  getCustomize()
  getAssetCustomize()
}
function getList() {
  return new Promise((resolve) => {
    setTimeout(() => {
      let tableData = tableInfo.value.data
      // 阻断 vue 对大数组的监听，避免 vue 绑定大数据造成短暂的卡顿
      if (proxy.$refs.xTable) {
        proxy.$refs.xTable.loadData(tableData)
      }
      resolve()
    }, 300)
  })
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      let data = tableInfo.value.data
      let assetIds = data.map((item) => item.id)
      let param = {
        ...formInfo.value.data,
        assetIds: assetIds,
      }
      saveAssetDepreciation(param).then((res) => {
        if (res && res.success) {
          showDialog.value = false
          emits('returnModify', false)
        }
      })
    }
  })
}
function onCallBackScanData(data, callback) {
  if (data && data.assetCode) {
    data.assetVersion = data.version
    data.assetId = data.id
    if (tableInfo.value.data) {
      tableInfo.value.data.forEach((item) => {
        item.isChoice = false
      })
      let index = tableInfo.value.data.findIndex(
        (item) => item.assetCode === data.assetCode
      )
      if (index !== -1) {
        callback(true)
      } else {
        tableInfo.value.data.unshift(data)
        getList()
        callback(false)
      }
    } else {
      tableInfo.value.data.unshift(data)
      getList()
      callback(true)
    }
  }
}
function addProduct() {
  if (tableInfo.value.data.length) {
    selectAssetInfo.value.query.queryMap.id.value = tableInfo.value.data
      .map((item) => item.id)
      .toString()
  } else {
    selectAssetInfo.value.query.queryMap.id.value = ''
  }
  selectAssetInfo.value.visible = true
}
function addAllProduct() {
  //选择全部资产
  allAssetFilterInfo.value.queryMap = proxy.$fn.deepClone(
    selectAssetInfo.value.query.queryMap
  )
  allAssetFilterInfo.value.queryParams = proxy.$fn.deepClone(
    selectAssetInfo.value.query.queryParams
  )
  allAssetFilterInfo.value.queryMap.id.value = ''
  getAssetCardAll(allAssetFilterInfo.value).then((res) => {
    if (res && res.success) {
      if (!res.data.length) {
        proxy.$message({
          message: '无可折旧数据',
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
        return
      }
      res.data.forEach((item) => {
        item.adjustBefore = item.originalAmount
        item.assetId = item.id
      })
      tableInfo.value.data = res.data
      getList()
    }
  })
}
function getAssetCustomize() {
  let param = { tableKey: selectAssetInfo.value.tableKey }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      allAssetFilterInfo.value.customizeUserVO = data
    }
  })
}
function handleEvent(event, data) {
  console.log(data)
  tableInfo.value.selections = data
  // switch (event) {
  //   case 'tableClickRow':
  //     selectRow.value = data
  //     break
  //   case 'tableCheck':
  //     if (data.length) {
  //       selectRow.value = data
  //     }
  //     break
  // }
}
// function selectChange(data) {
//   tableInfo.value.selections = data.records
// }
// function toggleAllPaperSelect(data) {
//   tableInfo.value.selections = data.records
// }

function removeProduct(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
    getList()
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
        getList()
      })
  }
}
function callBackAsset(data) {
  data.forEach((item) => {
    item.adjustBefore = item.originalAmount
    item.assetVersion = item.version
    item.assetId = item.id
  })
  tableInfo.value.data = data.concat(tableInfo.value.data)
  getList()
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'assetAssetManageDepreciationModify-com.slip.spd.entity.vo.asset.AssetDepreciationVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      proxy.$nextTick(() => {
        let data = res.data
        filterInfo.value.query.customizeUserVO = data
        let obj = proxy.$fn.setFieldList(
          tableInfo.value.fieldList,
          data.detail,
          true
        )
        tableInfo.value.fieldList = obj.fieldList
      })
    }
  })
}
//表尾合计
function footerMethod({ columns, data }) {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return '合计'
      }
      switch (column.property) {
        case 'monthDeprAmount':
          return parseInt(XEUtils.sum(data, column.property))
      }
      return null
    }),
  ]
}
</script>
